package com.api.apigateway;

import com.api.apicommon.model.entity.InterfaceInfo;
import com.api.apicommon.model.entity.User;
import com.api.apicommon.service.InnerInterfaceInfoService;
import com.api.apicommon.service.InnerUserInterfaceInfoService;
import com.api.apicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Slf4j
@Component
public class CustomGlobaFilter implements GlobalFilter, Ordered {
    //用户信息，需要得到用户的信息
    @DubboReference
    InnerUserService userService;
    @DubboReference
    InnerInterfaceInfoService interfaceInfoService;
    //需要统计接口的被调用次数
    @DubboReference
    InnerUserInterfaceInfoService userInterfaceInfoService;
    //接口地址
    private static final String INTERFACE_HOST = "http://localhost:8098";
    //允许访问的地址(白名单)
    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");
    //记录nonce的值
    public static final List<Long> NONCE_LIST = new ArrayList<>();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /**
         * 1.exchange拿到 请求信息
         * 2.进行相关业务的判断，有异常返回异常数据
         * 3.降级处理数据
         */
        ServerHttpRequest request = exchange.getRequest();
        //返回信息
        ServerHttpResponse response = exchange.getResponse();
        //请求路径
        String path = INTERFACE_HOST + request.getPath().value();
        String method = request.getMethod().toString();
        //1. 白名单
        String sourceAddress = request.getLocalAddress().getHostString();
        if(!IP_WHITE_LIST.contains(sourceAddress)){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            //返回403的错误
            return response.setComplete();
        }
        //2. 用户鉴权（判断accessKey是否合法,防止重放的话加上了timestamp,sign 签名）
        //2.1 获取相关参数
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body = headers.getFirst("body");
        //2.2 TODO 获取到用户的信息进行校验
        User invokeUser = null;
        try{
            invokeUser= userService.getInvokeUser(accessKey);
        }catch (Exception e){
            return handleNoAuth(response);
        }
        if(invokeUser == null)return handleNoAuth(response);
        //2.3
        //2.3.1 判断时间是否符合要求 一般是15分钟 这个可以根据需求来，主要目的是为了防止nonce的值过多，导致服务的内存爆满
        Long currentTime = System.currentTimeMillis() / 1000;
        final Long FIFTEEN = 60 * 15L;
        if(currentTime - Long.parseLong(timestamp) >= FIFTEEN){
            return handleNoAuth(response);
        }
        //2.3.2 时间符合要求的话则 进行nonce的判断，最好的办法是使用redis的set集合并判断过期时间
        if(NONCE_LIST.contains(Long.parseLong(nonce))){
            return handleNoAuth(response);
        }
        NONCE_LIST.add(Long.parseLong(nonce));
        //3 TODO 获取接口信息
        InterfaceInfo interfaceInfo = null;
        try{
            //校验数据库中是否有该接口的信息
            interfaceInfo = interfaceInfoService.getInterfaceInfo(path,method);
        }catch (Exception e){
            log.error("getInterfaceInfo error",e);
        }
        if(interfaceInfo == null)return handleNoAuth(response);
        //4. TODO 请求转发，调用模式接口 + 响应日志
        //  Mono<Void> filter = chain.filter(exchange);
        //  return filter;
        return handleResponse(exchange,chain,interfaceInfo.getId(),invokeUser.getId());
    }

    /**
     * 处理接口返回的数据
     * @param exchange  交换机
     * @param chain  响应链
     * @param interfaceId  接口id
     * @param userId  用户id
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange,GatewayFilterChain chain,long interfaceId,long userId){
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();

            HttpStatus statusCode = originalResponse.getStatusCode();

            if(statusCode == HttpStatus.OK){
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                try{
                                    userInterfaceInfoService.invokeCount(interfaceId,userId);
                                }catch (Exception e){
                                    log.error("invokeCount error" + e);
                                }
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                sb2.append("<--- {} {} \n");
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);
                                log.info(sb2.toString(), rspArgs.toArray());//log.info("<-- {} {}\n", originalResponse.getStatusCode(), data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        }catch (Exception e){
            log.error("网关请求异常" + e);
            return chain.filter(exchange);
        }
    }
    /**
     * 无权限
     */
    public Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }
    /**
     * 调用接口失败
     */
    public Mono<Void> handleInvokeError(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
    /**
     * 过滤器的执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
